package top.hg.tool.common.util;


import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 对象转化工具类
 * Created by skh on 2018/7/11.
 */
public class ConvertUtil {


	public static <D> D convert(Object source, Class<D> targetClass) {
		if (source == null) {
			return null;
		}
		try {
			Object target = targetClass.newInstance();
			BeanUtils.copyProperties(source, target);
			return (D) target;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


	public static <T> List<T> convertList(List sourceList, Class<T> targetClass) {
		if (sourceList == null || sourceList.size() == 0) {
			return new ArrayList<>();
		}
		try {
			ArrayList<T> resultList = new ArrayList<>();
			for (Object source : sourceList) {
				T target = targetClass.newInstance();
				BeanUtils.copyProperties(source, target);
				resultList.add(target);
			}
			return resultList;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
